package com.netsdk.demo.customize;

import com.netsdk.demo.util.CaseMenu;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.lib.callback.impl.DefaultDisconnectCallback;
import com.netsdk.lib.callback.impl.DefaultHaveReconnectCallBack;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;

import static com.netsdk.lib.NetSDKLib.*;
import static com.netsdk.lib.NetSDKLib.EM_NET_AUTHORITY_TYPE.NET_AUTHORITY_OPEN_GATE;
import static com.netsdk.lib.NetSDKLib.EM_NET_RECORD_TYPE.NET_RECORD_TRAFFICBLACKLIST;
import static com.netsdk.lib.NetSDKLib.EM_RECORD_OPERATE_TYPE.NET_TRAFFIC_LIST_INSERT;
import static com.netsdk.lib.Utils.getOsPrefix;

/**
 * @author 291189
 * @version 1.0
 * @description GIP230217016
 * @date 2023/2/22 9:14
 */
public class TrafficListDemo {
    // SDk对象初始化
    public static final NetSDKLib netsdk = NetSDKLib.NETSDK_INSTANCE;
    public static final NetSDKLib configsdk = NetSDKLib.CONFIG_INSTANCE;

    // 判断是否初始化
    private static boolean bInit = false;
    // 判断log是否打开
    private static boolean bLogOpen = false;
    // 设备信息
    private NetSDKLib.NET_DEVICEINFO_Ex deviceInfo = new NetSDKLib.NET_DEVICEINFO_Ex();
    // 登录句柄
    private NetSDKLib.LLong m_hLoginHandle = new NetSDKLib.LLong(0);

    // 智能事件订阅句柄
    private NetSDKLib.LLong m_attachHandle = new NetSDKLib.LLong(0);

    // 回调函数需要是静态的，防止被系统回收
    // 断线回调
    private static NetSDKLib.fDisConnect disConnectCB = DefaultDisconnectCallback.getINSTANCE();
    // 重连回调
    private static NetSDKLib.fHaveReConnect haveReConnectCB = DefaultHaveReconnectCallBack.getINSTANCE();

    // 编码格式
    public static String encode;

    static {
        String osPrefix = getOsPrefix();
        if (osPrefix.toLowerCase().startsWith("win32-amd64")) {
            encode = "GBK";
        } else if (osPrefix.toLowerCase().startsWith("linux-amd64")) {
            encode = "UTF-8";
        }
    }

    /**
     * 获取当前时间
     */
    public static String GetDate() {
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDate.format(new java.util.Date()).replaceAll("[^0-9]", "-");
    }

    /**
     * 初始化SDK库
     */
    public static boolean Init() {
        bInit = netsdk.CLIENT_Init(disConnectCB, null);// 进程启动时，初始化一次
        if (!bInit) {
            System.out.println("Initialize SDK failed");
            return false;
        }
        // 配置日志
        TrafficListDemo.enableLog();

        // 设置断线重连回调接口, 此操作为可选操作，但建议用户进行设置
        netsdk.CLIENT_SetAutoReconnect(haveReConnectCB, null);

        // 设置登录超时时间和尝试次数，可选
        // 登录请求响应超时时间设置为3S
        int waitTime = 3000;
        // 登录时尝试建立链接 1 次
        int tryTimes = 1;
        netsdk.CLIENT_SetConnectTime(waitTime, tryTimes);
        // 设置更多网络参数， NET_PARAM 的nWaittime ， nConnectTryNum 成员与 CLIENT_SetConnectTime
        // 接口设置的登录设备超时时间和尝试次数意义相同,可选
        NetSDKLib.NET_PARAM netParam = new NetSDKLib.NET_PARAM();
        // 登录时尝试建立链接的超时时间
        netParam.nConnectTime = 10000;
        // 设置子连接的超时时间
        netParam.nGetConnInfoTime = 3000;
        netsdk.CLIENT_SetNetworkParam(netParam);
        return true;
    }

    /**
     * 打开 sdk log
     */
    private static void enableLog() {
        NetSDKLib.LOG_SET_PRINT_INFO setLog = new NetSDKLib.LOG_SET_PRINT_INFO();
        File path = new File("sdklog/");
        if (!path.exists())
            path.mkdir();

        // 这里的log保存地址依据实际情况自己调整
        String logPath = path.getAbsoluteFile().getParent() + "\\sdklog\\" + "sdklog" + GetDate() + ".log";
        setLog.nPrintStrategy = 0;
        setLog.bSetFilePath = 1;
        System.arraycopy(logPath.getBytes(), 0, setLog.szLogFilePath, 0, logPath.getBytes().length);
        System.out.println(logPath);
        setLog.bSetPrintStrategy = 1;
        bLogOpen = netsdk.CLIENT_LogOpen(setLog);
        if (!bLogOpen)
            System.err.println("Failed to open NetSDK log");
    }

    /**
     * 高安全登录
     */
    public void loginWithHighLevel() {
        // 输入结构体参数
        NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstlnParam = new NetSDKLib.NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY() {
            {
                szIP = m_strIpAddr.getBytes();
                nPort = m_nPort;
                szUserName = m_strUser.getBytes();
                szPassword = m_strPassword.getBytes();
            }
        };
        // 输出结构体参数
        NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam = new NetSDKLib.NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();

        // 写入sdk
        m_hLoginHandle = netsdk.CLIENT_LoginWithHighLevelSecurity(pstlnParam, pstOutParam);
        if (m_hLoginHandle.longValue() == 0) {
            System.err.printf("Login Device[%s] Port[%d]Failed. %s\n", m_strIpAddr, m_nPort,
                    netsdk.CLIENT_GetLastError());
        } else {
            deviceInfo = pstOutParam.stuDeviceInfo; // 获取设备信息
            System.out.println("Login Success");
            System.out.println("Device Address：" + m_strIpAddr);
            System.out.println("设备包含：" + deviceInfo.byChanNum + "个通道");
        }
    }

    /**
     * 退出
     */
    public void logOut() {
        if (m_hLoginHandle.longValue() != 0) {
            netsdk.CLIENT_Logout(m_hLoginHandle);
            System.out.println("LogOut Success");
        }
    }

    /**
     * 清理sdk环境并退出
     */
    public static void cleanAndExit() {
        if (bLogOpen) {
            netsdk.CLIENT_LogClose(); // 关闭sdk日志打印
        }
        netsdk.CLIENT_Cleanup(); // 进程关闭时，调用一次
        System.exit(0);
    }


    /**
     * 批量导入禁止允许名单,导入时车牌号不能重复
     */
    public void insertCard() {
        NetSDKLib.NET_CTRL_RECORDSET_INSERT_PARAM stInfo=new NetSDKLib.NET_CTRL_RECORDSET_INSERT_PARAM();

        stInfo.stuCtrlRecordSetInfo.emType = NET_RECORD_TRAFFICBLACKLIST;

        NetSDKLib.NET_TRAFFIC_LIST_RECORD pstRecord=new  NetSDKLib.NET_TRAFFIC_LIST_RECORD();

        String number="浙B88887";
        byte[] szPlateNumber
                = pstRecord.szPlateNumber;
        ToolKits.StringToByteArr(number,szPlateNumber);

        String masterOfCar="abcd";
        byte[] szMasterOfCar = pstRecord.szMasterOfCar;

        ToolKits.StringToByteArr(masterOfCar,szMasterOfCar);

        NetSDKLib.NET_TIME beginTime
                = new NetSDKLib.NET_TIME();
        beginTime.setTime(2023,1,20,0,0,0);
        pstRecord.stBeginTime = beginTime;

        NetSDKLib.NET_TIME cancelTime
                = new NetSDKLib.NET_TIME();
        cancelTime.setTime(2023,2,20,0,0,0);

        pstRecord.stCancelTime = cancelTime;
        pstRecord.nAuthrityNum = 1;
        //权限类型，对应EM_NET_AUTHORITY_TYPE
        pstRecord.stAuthrityTypes[0].emAuthorityType = NET_AUTHORITY_OPEN_GATE;
        //权限使能
        pstRecord.stAuthrityTypes[0].bAuthorityEnable = 1;
        /**
         布控路线ID
         */
        pstRecord.nControlledRouteID = 1;


        stInfo.stuCtrlRecordSetInfo.pBuf=new Memory(pstRecord.dwSize);

        stInfo.stuCtrlRecordSetInfo.pBuf.clear(pstRecord.dwSize);

        ToolKits.SetStructDataToPointer(pstRecord,  stInfo.stuCtrlRecordSetInfo.pBuf,0);

        Pointer stInfoPointer =new Memory(stInfo.dwSize);

        stInfoPointer.clear(stInfo.dwSize);

        ToolKits.SetStructDataToPointer(stInfo,stInfoPointer,0);

        boolean b = netsdk.CLIENT_ControlDevice(m_hLoginHandle, NetSDKLib.CtrlType.CTRLTYPE_CTRL_RECORDSET_INSERT, stInfoPointer, 3000);

        if(b){
            System.out.println("CLIENT_ControlDevice success");
        }else {
            System.out.println("CLIENT_ControlDevice fail:"+ToolKits.getErrorCode());
        }

        ToolKits.GetPointerData(stInfoPointer,stInfo);

        Native.free(Pointer.nativeValue(stInfoPointer));//清理内存
        Pointer.nativeValue(stInfoPointer, 0);
    }

    /**
     * 添加黑名单
     */
    public void operateTrafficList(){

        NetSDKLib.NET_IN_OPERATE_TRAFFIC_LIST_RECORD stIn = new NetSDKLib.NET_IN_OPERATE_TRAFFIC_LIST_RECORD();

        stIn.emOperateType = NET_TRAFFIC_LIST_INSERT;

        stIn.emRecordType = NET_RECORD_TRAFFICBLACKLIST;

        NetSDKLib.NET_TRAFFIC_LIST_RECORD.ByReference pstRecord = new NetSDKLib.NET_TRAFFIC_LIST_RECORD.ByReference();
        byte[] szPlateNumber
                = pstRecord.szPlateNumber;

        String number="浙A88888";
        ToolKits.StringToByteArr(number,szPlateNumber);

        byte[] szMasterOfCar
                = pstRecord.szMasterOfCar;
        String masterOfCar="ABC";
        ToolKits.StringToByteArr(masterOfCar,szMasterOfCar);


        NetSDKLib.NET_TIME beginTime
                = new NetSDKLib.NET_TIME();
        beginTime.setTime(2023,1,20,0,0,0);
        pstRecord.stBeginTime = beginTime;

        NetSDKLib.NET_TIME cancelTime
                = new NetSDKLib.NET_TIME();
        cancelTime.setTime(2023,2,20,0,0,0);
        pstRecord.stCancelTime = cancelTime;

        pstRecord.nAuthrityNum = 1;
        pstRecord.stAuthrityTypes[0].emAuthorityType = NET_AUTHORITY_OPEN_GATE;
        pstRecord.stAuthrityTypes[0].bAuthorityEnable = 1;
        pstRecord.nControlledRouteID = 1;


        NetSDKLib.NET_INSERT_RECORD_INFO pInfo = new NetSDKLib.NET_INSERT_RECORD_INFO();

        pInfo.pRecordInfo = pstRecord;

        stIn.pstOpreateInfo=new Memory(pInfo.dwSize);

        stIn.pstOpreateInfo.clear(pInfo.dwSize);

        ToolKits.SetStructDataToPointer(pInfo, stIn.pstOpreateInfo,0);

        NetSDKLib.NET_OUT_OPERATE_TRAFFIC_LIST_RECORD stOut = new NetSDKLib.NET_OUT_OPERATE_TRAFFIC_LIST_RECORD();


        boolean b = netsdk.CLIENT_OperateTrafficList(m_hLoginHandle, stIn, stOut, 5000);

        if (b)
        {
            System.out.println("set success\n");
        }
        else
        {
            System.out.println("Set Failed, error is :"+ToolKits.getErrorCode());
        }

    }



    public void findRecord(){

        NetSDKLib.NET_IN_FIND_RECORD_PARAM stIn = new NetSDKLib.NET_IN_FIND_RECORD_PARAM();
        stIn.emType = NET_RECORD_TRAFFICBLACKLIST;
        NetSDKLib.FIND_RECORD_TRAFFICREDLIST_CONDITION stCondition = new NetSDKLib.FIND_RECORD_TRAFFICREDLIST_CONDITION();
        stIn.pQueryCondition= new Memory(stCondition.dwSize);
        stIn.pQueryCondition.clear(stCondition.dwSize);

        ToolKits.SetStructDataToPointer(stCondition,stIn.pQueryCondition,0);

        NetSDKLib.NET_OUT_FIND_RECORD_PARAM stOut = new NetSDKLib.NET_OUT_FIND_RECORD_PARAM();

        boolean bRet = netsdk.CLIENT_FindRecord(m_hLoginHandle, stIn, stOut, 5000);
        if (bRet)
        {
            NetSDKLib.NET_IN_FIND_NEXT_RECORD_PARAM stNextIn =new  NetSDKLib.NET_IN_FIND_NEXT_RECORD_PARAM();
            stNextIn.lFindeHandle = stOut.lFindeHandle;
            stNextIn.nFileCount = 32;

            NetSDKLib.NET_OUT_FIND_NEXT_RECORD_PARAM stNextOut = new NetSDKLib.NET_OUT_FIND_NEXT_RECORD_PARAM();

            NetSDKLib.NET_TRAFFIC_LIST_RECORD[] pRecord = new NetSDKLib.NET_TRAFFIC_LIST_RECORD[32];
            for (int i = 0; i < pRecord.length; ++i)
            {
                pRecord[i] =new  NetSDKLib.NET_TRAFFIC_LIST_RECORD();
            }
            stNextOut.nMaxRecordNum =32;

            stNextOut.pRecordList = new Memory(new  NetSDKLib.NET_TRAFFIC_LIST_RECORD().dwSize*32);

            stNextOut.pRecordList.clear(new  NetSDKLib.NET_TRAFFIC_LIST_RECORD().dwSize*32 );

            ToolKits.SetStructArrToPointerData(pRecord,stNextOut.pRecordList);

                    bRet = netsdk.CLIENT_FindNextRecord(stNextIn, stNextOut, 3000);
            if (bRet)
            {

                ToolKits.GetPointerDataToStructArr(stNextOut.pRecordList,pRecord);

                for (int i = 0; i < stNextOut.nRetRecordNum; ++i)
                {
                    NetSDKLib.NET_TRAFFIC_LIST_RECORD stuRecord = pRecord[i];
                    try {
                        System.out.println("szPlateNumber:"+new String(stuRecord.szPlateNumber,encode));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    System.out.println("nControlledRouteID:"+stuRecord.nControlledRouteID);
                }
                netsdk.CLIENT_FindRecordClose(stOut.lFindeHandle);
            }
        }
    }

    /**
     * 选择通道
     */
    private int channelId = 1;// 逻辑通道
    /**
     * 订阅智能任务
     */
    public void AttachEventRealLoadPic() {
        // 先退订，设备不会对重复订阅作校验，重复订阅后会有重复的事件返回
        this.DetachEventRealLoadPic();
        // 需要图片
        int bNeedPicture = 1;
        //EVENT_IVS_ALL 表示订阅所有智能事件
        m_attachHandle = netsdk.CLIENT_RealLoadPictureEx(m_hLoginHandle, channelId, EVENT_IVS_ALL, bNeedPicture, AnalyzerDataCB.getInstance(), null, null);

        if (m_attachHandle.longValue() != 0) {
            System.out.printf("Chn[%d] CLIENT_RealLoadPictureEx Success\n", channelId);
        } else {
            System.out.printf("Ch[%d] CLIENT_RealLoadPictureEx Failed!LastError = %s\n", channelId,
                    ToolKits.getErrorCode());
        }
    }

    /**
     * 报警事件（智能）回调
     */
    private static class AnalyzerDataCB implements NetSDKLib.fAnalyzerDataCallBack {
        private final File picturePath;
        private static AnalyzerDataCB instance;

        private AnalyzerDataCB() {
            picturePath = new File("./AnalyzerPicture/");
            if (!picturePath.exists()) {
                picturePath.mkdirs();
            }
        }

        public static AnalyzerDataCB getInstance() {
            if (instance == null) {
                synchronized (AnalyzerDataCB.class) {
                    if (instance == null) {
                        instance = new AnalyzerDataCB();
                    }
                }
            }
            return instance;
        }

        @Override
        public int invoke(NetSDKLib.LLong lAnalyzerHandle, int dwAlarmType, Pointer pAlarmInfo, Pointer pBuffer, int dwBufSize,
                          Pointer dwUser, int nSequence, Pointer reserved) {
            if (lAnalyzerHandle == null || lAnalyzerHandle.longValue() == 0) {
                return -1;
            }

            switch (dwAlarmType) {
               case EVENT_IVS_TRAFFICJUNCTION : {//    // 交通路口事件----老规则(对应 DEV_EVENT_TRAFFICJUNCTION_INFO)
                   System.out.println("交通路口事件");
                   //路口事件，抓拍车牌
                   NetSDKLib.DEV_EVENT_TRAFFICJUNCTION_INFO trafficJunction=new NetSDKLib.DEV_EVENT_TRAFFICJUNCTION_INFO();
                   //获取车牌信息
                   ToolKits.GetPointerDataToStruct(pAlarmInfo,0,trafficJunction);
                   String date
                           = trafficJunction.UTC.toStringTime();
                   NetSDKLib.DEV_EVENT_TRAFFIC_TRAFFICCAR_INFO trafficCar=trafficJunction.stTrafficCar;
                   try {
                       System.out.println(date+" traffic number:"+new String(trafficCar.szPlateNumber,
                               encode)+",plate color:"+
                               new String(trafficCar.szPlateColor,encode));
                   } catch (UnsupportedEncodingException e) {
                       e.printStackTrace();
                   }
                   System.out.println("emVehicleTypeByFunc = " + trafficJunction.stTrafficCar.emVehicleTypeByFunc);
                   System.out.println("nSunBrand = " + trafficJunction.stTrafficCar.nSunBrand);
                   System.out.println("nBrandYear = " + trafficJunction.stTrafficCar.nBrandYear);
                   //save the picture
                   String   imageName="trafficJunction_"+trafficJunction.UTC.toStringTitle()+".jpg";

                   String   savePath=picturePath+"/"+imageName;

                   ToolKits.savePicture(pBuffer,dwBufSize,savePath);
                   System.out.println("save picture to "+savePath);

                   NET_TRAFFICCAR_BLACK_LIST stuBlackList
                           = trafficCar.stuBlackList;
                   int nControlledRouteID
                           = stuBlackList.nControlledRouteID;

                   System.out.println("nControlledRouteID = " + nControlledRouteID);
                   break;

                }
                default:
                    System.out.println("其他事件--------------------"+ dwAlarmType);
                    break;
            }
            return 0;
        }
    }

    /**
     * 停止侦听智能事件
     */
    public void DetachEventRealLoadPic() {
        if (m_attachHandle.longValue() != 0) {
            netsdk.CLIENT_StopLoadPic(m_attachHandle);
        }
    }


    public void RunTest()
    {
        System.out.println("Run Test");
        CaseMenu menu = new CaseMenu();;
        menu.addItem((new CaseMenu.Item(this , "insertCard" , "insertCard")));
        menu.addItem((new CaseMenu.Item(this , "operateTrafficList" , "operateTrafficList")));

        menu.addItem((new CaseMenu.Item(this , "findRecord" , "findRecord")));
        menu.addItem((new CaseMenu.Item(this , "AttachEventRealLoadPic" , "AttachEventRealLoadPic")));
        menu.addItem((new CaseMenu.Item(this , "DetachEventRealLoadPic" , "DetachEventRealLoadPic")));

        menu.run();
    }
    // 配置登陆地址，端口，用户名，密码
    private String m_strIpAddr = "172.32.10.26";
    private int m_nPort = 37777;
    private String m_strUser = "admin";
    private String m_strPassword = "admin123";
    public static void main(String[] args) {
        TrafficListDemo demo=new TrafficListDemo();
        demo.InitTest();
        demo.RunTest();
        demo.EndTest();

    }

    /**
     * 初始化测试
     */
    public void InitTest() {
        TrafficListDemo.Init();
        this.loginWithHighLevel();
    }

    /**
     * 结束测试
     */
    public void EndTest() {
        System.out.println("End Test");
        this.logOut(); // 登出设备
        System.out.println("See You...");
        TrafficListDemo.cleanAndExit(); // 清理资源并退出
    }
}
